package com.kangyi.user.service.Impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kangyi.constant.MessageConstant;
import com.kangyi.dto.NursingHomeReviewDTO;
import com.kangyi.dto.NursingHomeReviewImageDTO;
import com.kangyi.dto.ReviewPageQueryDTO;
import com.kangyi.entity.*;
import com.kangyi.exception.DataNotExistException;
import com.kangyi.result.PageResult;
import com.kangyi.user.mapper.*;
import com.kangyi.user.service.NursingHomeReviewService;
import com.kangyi.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Blank
 * @version 1.0
 */
@Service
@Slf4j
public class NursingHomeReviewServiceImpl implements NursingHomeReviewService {

    @Autowired
    private NursingHomeReviewMapper nursingHomeReviewMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private NursingHomeReviewImageMapper nursingHomeReviewImageMapper;

    @Autowired
    private NursingHomeBookingMapper nursingHomeBookingMapper;

    @Autowired
    private GuestsStayingMapper guestsStayingMapper;

    @Autowired
    private NursingHomeReviewReplyMapper nursingHomeReviewReplyMapper;

    @Override
    public List<NursingHomeReviewListVO> listReview(Integer userId) {

        User user = userMapper.getUsersById(userId);
        if (user == null) {
            throw new DataNotExistException(MessageConstant.DATA_NOT_EXIST);
        }

        // 处理评价列表为空的情况
        List<NursingHomeReviewListVO> nursingHomeReviewListVO = nursingHomeReviewMapper.listReview(userId);
        if (CollUtil.isEmpty(nursingHomeReviewListVO)) {
            throw new DataNotExistException(MessageConstant.DATA_NOT_EXIST);
        }

        for (NursingHomeReviewListVO reviewListVO : nursingHomeReviewListVO) {
            Integer reviewId = reviewListVO.getId();
            NursingHomeReviewReplyVO nursingHomeReviewReplyVO = nursingHomeReviewReplyMapper.getReviewReplyByReviewId(reviewId);
            reviewListVO.setNursingHomeReviewReplyVO(nursingHomeReviewReplyVO);
        }

        return nursingHomeReviewListVO;
    }

    @Override
    public void deleteReview(Integer id) {

        NursingHomeReview nursingHomeReview = nursingHomeReviewMapper.selectById(id);
        if (nursingHomeReview == null) {
            throw new DataNotExistException(MessageConstant.DATA_NOT_EXIST);
        }
        List<NursingHomeReviewImage> nursingHomeReviewImageList = nursingHomeReviewImageMapper.selectByReviewId(id);
        if (CollUtil.isEmpty(nursingHomeReviewImageList)) {
            nursingHomeReviewMapper.deleteById(id);
            return;
        }

        nursingHomeReviewImageMapper.deleteByReviewId(id);
        nursingHomeReviewMapper.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 开启事务
    public void releaseReview(NursingHomeReviewDTO nursingHomeReviewDTO) {
        // 修改后的查询逻辑
        NursingHomeBooking nursingHomeBooking = nursingHomeBookingMapper.selectByUserIdAndNursingHomeId(nursingHomeReviewDTO.getUserId(), nursingHomeReviewDTO.getNursingHomeId());
        GuestsStaying guestsStaying = guestsStayingMapper.selectByUserIdAndNursingHomeId(nursingHomeReviewDTO.getUserId(), nursingHomeReviewDTO.getNursingHomeId());

        if (guestsStaying == null && nursingHomeBooking == null) {
            throw new DataNotExistException(MessageConstant.PLEASE_MAKE_AN_APPOINTMENT_OR_JOIN_THIS_NURSING_HOME_BEFORE_LEAVING_A_COMMENT);
        }

        // DTO 转换为实体
        NursingHomeReview nursingHomeReview = new NursingHomeReview();
        BeanUtils.copyProperties(nursingHomeReviewDTO, nursingHomeReview);

        // **确保 MyBatis 返回自增 ID**
        nursingHomeReviewMapper.releaseReview(nursingHomeReview);

        // **获取自增 ID**
        Integer reviewId = nursingHomeReview.getId();
        if (reviewId == null) {
            log.error("插入评论后 ID 为空，无法关联图片信息");
            throw new RuntimeException("评论 ID 为空，插入失败");
        }

        List<NursingHomeReviewImageDTO> imageDTOList = nursingHomeReviewDTO.getNursingHomeReviewImageDTOList();
        if (imageDTOList != null && !imageDTOList.isEmpty()) {
            List<NursingHomeReviewImage> imageList = new ArrayList<>();
            for (NursingHomeReviewImageDTO dto : imageDTOList) {
                NursingHomeReviewImage image = new NursingHomeReviewImage();
                BeanUtils.copyProperties(dto, image);
                image.setNursingHomeReviewId(reviewId); // 绑定 ID
                imageList.add(image);
            }

            // **批量插入**
            if (!imageList.isEmpty()) {
                try {
                    nursingHomeReviewImageMapper.insertBatch(imageList);
                } catch (Exception e) {
                    log.error("插入评论图片失败", e);
                    throw new RuntimeException("插入评论图片失败", e);
                }
            }
        }
    }

    @Override
    public PageResult pageReview(ReviewPageQueryDTO reviewPageQueryDTO) {
        PageHelper.startPage(reviewPageQueryDTO.getPage(),reviewPageQueryDTO.getPageSize());
        Page<ReviewPageVO> page = nursingHomeReviewMapper.pageQuery(reviewPageQueryDTO);
        long total = page.getTotal();
        List<ReviewPageVO> result = page.getResult();
        return new PageResult(total,result);
    }
}
